package model

import (
	"time"
	"user_srv/basic/config"
)

// 用户好友关系表（单向记录，互为好友存两条）
type XqUserFriends struct {
	Id        int64     `gorm:"column:id;type:bigint;primaryKey;not null;" json:"id"`
	UserId    int64     `gorm:"column:user_id;type:bigint;not null;index;comment:所属用户ID;" json:"user_id"`
	FriendId  int64     `gorm:"column:friend_id;type:bigint;not null;index;comment:好友用户ID;" json:"friend_id"`
	GroupId   int64     `gorm:"column:group_id;type:bigint;default:0;comment:所属分组ID;" json:"group_id"`
	Remark    string    `gorm:"column:remark;type:varchar(50);comment:备注名;" json:"remark"`
	IsActive  int8      `gorm:"column:is_active;type:tinyint(1);default:1;comment:是否有效;" json:"is_active"`
	CreatedAt time.Time `gorm:"column:created_at;type:timestamp;default:CURRENT_TIMESTAMP;" json:"created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;default:CURRENT_TIMESTAMP;" json:"updated_at"`
}

func (x *XqUserFriends) TableName() string { return "xq_user_friends" }

func (x *XqUserFriends) Create() error { return config.DB.Create(&x).Error }

func (x *XqUserFriends) Update(where XqUserFriends) error {
	return config.DB.Where(where).Updates(&x).Error
}

func (x *XqUserFriends) Delete(where XqUserFriends) error {
	return config.DB.Where(where).Delete(&x).Error
}

func (x *XqUserFriends) IsFriend(userId, friendId int64) (bool, error) {
	var cnt int64
	err := config.DB.Model(&XqUserFriends{}).Where("user_id = ? AND friend_id = ? AND is_active = 1", userId, friendId).Count(&cnt).Error
	return cnt > 0, err
}

func (x *XqUserFriends) ListByGroup(userId, groupId int64) ([]XqUserFriends, error) {
	var list []XqUserFriends
	err := config.DB.Where("user_id = ? AND group_id = ? AND is_active = 1", userId, groupId).Find(&list).Error
	return list, err
}

func (x *XqUserFriends) ListAll(userId int64) ([]XqUserFriends, error) {
	var list []XqUserFriends
	err := config.DB.Where("user_id = ? AND is_active = 1", userId).Find(&list).Error
	return list, err
}
